#include "mainwindow.h"
#include "ui_mainwindow.h"

// 连接
void MainWindow::on_btn_link_disp_f210_clicked()
{
    if(LangureStu == 1)
    {
        LangureStr = "Connect";
    }
    else
    {
        LangureStr = "连  接";
    }
    Btn_Lock_Or_Unlock_Disp_F210(DISP_BTN_LOCK_ALL);
    ui->btn_link_disp_f210->setEnabled(false);
    ui->cbx_port_disp_f210->setEnabled(false);
    if(ui->btn_link_disp_f210->text() == LangureStr)
    {
        //下拉菜单控件失能
        ConnectStu_disp_f210 = 1;
        LangureStr_Init_Btn_Unlink(ui->btn_link_disp_f210);
        CPortName_disp_f210 = ui->cbx_port_disp_f210->currentText();
        if(!CPortName_disp_f210.isEmpty())
        {
            QString CPortName = CPortName_disp_f210.split(":").at(0);
            if(!ComThread_disp_f210->InitSerial(CPortName))
            {
                //打印出错提示
                if(LangureStu == 1)
                {
                    LangureStr = "Unable to open serial port";
                }
                else
                {
                    LangureStr = "无法打开串口";
                }
                InsertText(ui->te_prin_disp_f210, LangureStr, DLBOX_FONT_SIZE, APP_FONT_COLOR_WARNNING);
                LangureStr_Init_Btn_Link(ui->btn_link_disp_f210);
                ui->cbx_port_disp_f210->setEnabled(true);
                ui->btn_link_disp_f210->setEnabled(true);
                return;
            }
            RespData_disp_f210.clear();
            // 打印信息-设备检测
            LangureStr_Init_Testing(ui->te_prin_disp_f210);
            // 发送连接命令
            ComThread_disp_f210->SendSerial_LinkCmd_Link();
            while(RespData_disp_f210.isEmpty())QApplication::processEvents();
            if(F210_Cmd_Check(RespData_disp_f210))
            {
                //打印连接成功提示
                LangureStr_Init_Connected(ui->te_prin_disp_f210);
                ComThread_disp_f210->WaitTimer_TimeStart();
                Btn_Lock_Or_Unlock_Disp_F210(DISP_BTN_UNLOCK_ALL);
            }
            else
            {
                LangureStr_Init_Btn_Unlink(ui->btn_link_disp_f210);
                on_btn_link_disp_f210_clicked();
            }
        }
        else
        {
            if(ConnectStu_disp_f210 == 1)
            {
                LangureStr_Init_Btn_Unlink(ui->btn_link_disp_f210);
                on_btn_link_disp_f210_clicked();
                return;
            }
            else
            {
                LangureStr_Init_Btn_Link(ui->btn_link_disp_f210);
            }
        }
    }
    else
    {
        CPortName_disp_f210.clear();
        ComThread_disp_f210->CloseSerial();
        ui->cbx_port_disp_f210->setEnabled(true);

        LangureStr_Init_Btn_Link(ui->btn_link_disp_f210);
        LangureStr_Init_Unlink();
        if(ConnectStu_disp_f210)
        {
            LangureStr_Init_Disconnected();
            InsertText(ui->te_prin_disp_f210, LangureStr, DLBOX_FONT_SIZE, APP_FONT_COLOR_NORMAL);
        }
        ConnectStu_disp_f210 = 0;

        // 初始化按钮不可编辑
        Btn_Lock_Or_Unlock_Disp_F210(DISP_BTN_LOCK_ALL);
    }
    ui->btn_link_disp_f210->setEnabled(true);
}
// 数据接收
void MainWindow::disp_f210_data_receive(QByteArray data)
{
    QString ErrStr = data.split(':').at(0);
    QString bufferStr;
    if(!F210_Cmd_Check(data))
    {
        // 
        if(data.size() != 0)
        {
            if(data.at(0) == 0x55) //连接类
            {
                // dl400
            }
            else if(ErrStr == "timeout")
            {
                LangureStr_Init_TimeOut(ui->te_prin_disp_f210);
            }
            else if(ErrStr == "busy")
            {
                LangureStr_Init_Busy(ui->te_prin_disp_f210);
            }
            else
            {
                if(LangureStu == 1)
                {
                    LangureStr = "ERROR: Device validation failed.";
                }
                else
                {
                    LangureStr = "错误:设备验证失败。";
                }
                InsertText(ui->te_prin_disp_f210, LangureStr, DLBOX_FONT_SIZE, APP_FONT_COLOR_FAILED);
            }
        }
    }
    RespData_disp_f210 = data;
}

// 读gamma数据
void MainWindow::on_btn_disp_read_f210_clicked()
{
    // 获取文件路径
    QString FilePath = App_Btn_ChoosePath_GetPath("OpenDir/Dir");
    // 判断是否为空
    if(FilePath.isEmpty())
    {
        return;
    }
    Btn_Lock_Or_Unlock_Disp_F210(DISP_BTN_LOCK_ALL);
    LangureStr_Init_ReadingData(ui->te_prin_disp_f210);
    Read_Disp_Data_Form_Mcu(FilePath);
    Btn_Lock_Or_Unlock_Disp_F210(DISP_BTN_LOCK_RES);
}
#define disp_f210_file_name "screen_gamma_data_"
#define disp_f210_file_size 256
bool MainWindow::Read_Disp_Data_Form_Mcu(QString FilePath)
{
    // 判断是否存在系统命名文件名——存在则编号+1再次遍历，否则新建文件+.bak
    long icnt = 0;
    QString SaveFileName;
    while(1)
    {
#ifdef QT_DEBUG
        SaveFileName = FilePath + "/" + QString("%1%2.bin").arg(disp_f210_file_name).arg(icnt, 2, 10, QLatin1Char('0'));
#else

        SaveFileName = FilePath + "/" + QString("%1%2.dat").arg(disp_f210_file_name).arg(icnt, 2, 10, QLatin1Char('0'));
#endif
        bool exist = QFile::exists(SaveFileName);
        if(!exist)
        {
            break;
        }
        icnt++;
    }
    // 新建bak文件
    QString BakReadFileName = SaveFileName + ".bak";
    QFile BakReadFile(BakReadFileName);
    if(!BakReadFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
    {
        LangureStr_Init_FileOpenFail(ui->te_prin_disp_f210);
        return false;
    }
    // 清除同步显示框
    hexEdit_code_f210->clear();
    icnt = 0;
    QByteArray data;
    RespData_disp_f210.clear();
    ComThread_disp_f210->SendSerial_Read_GammaData(data, icnt);
    while(1)
    {
        while(RespData_disp_f210.isEmpty())QApplication::processEvents();
        if(F210_Cmd_Check(RespData_disp_f210))
        {
            if(RespData_disp_f210[7].operator==(0x15))
            {
                // 判断是否结束
                if(RespData_disp_f210[4].operator==(0xff))
                {
                    LangureStr_Init_ReadData_Succeed(ui->te_prin_disp_f210);
                    break;
                }
                // 将数据写入文件并同步显示
                else
                {
                    QByteArray Data_disp_f210;
                    Data_disp_f210.clear();
                    //取长度
                    int len = (((RespData_disp_f210[9]&0x00FF)<<8) & 0xFF00) | (RespData_disp_f210[8]&0x00FF);
                    Data_disp_f210.append(RespData_disp_f210.mid(12,len));
                    BakReadFile.write(Data_disp_f210);
                    hexEdit_code_f210->append(Data_disp_f210);
                }
            }
            else
            {
                LangureStr_Init_ReadData_Failed(ui->te_prin_disp_f210);
                BakReadFile.close();
                BakReadFile.remove();
                return false;
            }
        }
        else
        {
            BakReadFile.close();
            BakReadFile.remove();
            return false;
        }
        icnt++;
        RespData_disp_f210.clear();
        ComThread_disp_f210->SendSerial_LinkCmd_Wait();
    }
    //
    BakReadFile.close();

    bool exist = QFile::exists(SaveFileName);
    if(exist)
    {
        QFile::remove(SaveFileName);
    }
    exist = BakReadFile.rename(SaveFileName);
    if(LangureStu == 1)
    {
        LangureStr = "Saved to "+SaveFileName;
    }
    else
    {
       LangureStr = "已保存到 "+SaveFileName;
    }
    InsertText(ui->te_prin_disp_f210, LangureStr, NORMAL_FONT_SIZE, APP_FONT_COLOR_NORMAL);

    return true;
}
// 写gamma数据
void MainWindow::on_btn_disp_write_f210_clicked()
{
    // 获取文件路径
    QString FileName = App_Btn_ChooseFile_GetPath("OpenDir/Dir");
    // 判断是否为空
    if(FileName.isEmpty())
    {
        return;
    }
    Btn_Lock_Or_Unlock_Disp_F210(DISP_BTN_LOCK_ALL);
    LangureStr_Init_BurningData(ui->te_prin_disp_f210);
    Write_Disp_Data_Form_Mcu(FileName);
    Btn_Lock_Or_Unlock_Disp_F210(DISP_BTN_LOCK_RES);
}
//
bool MainWindow::Write_Disp_Data_Form_Mcu(QString WriteFileName)
{
    // 打开文件
    QFile WriteFile(WriteFileName);
    if(!WriteFile.open(QIODevice::ReadOnly | QIODevice::Truncate))
    {
        LangureStr_Init_FileOpenFail(ui->te_prin_disp_f210);
        return false;
    }
    // 清除同步显示框
    hexEdit_code_f210->clear();
    int icnt = 0;
    long Length = 0;
    char LineBuff[disp_f210_file_size];

    while(!WriteFile.atEnd()){
        Length = WriteFile.read(LineBuff, disp_f210_file_size);
        if(Length == disp_f210_file_size)
        {
            QByteArray WriteBuff;
            WriteBuff.resize(disp_f210_file_size);
            for (int icnt=0;icnt<disp_f210_file_size;icnt++) {
                WriteBuff[icnt] = LineBuff[icnt];
            }
            RespData_disp_f210.clear();
            ComThread_disp_f210->SendSerial_Write_GammaData(WriteBuff, icnt);
            while(RespData_disp_f210.isEmpty())QApplication::processEvents();
            if(F210_Cmd_Check(RespData_disp_f210))
            {
                if(RespData_disp_f210[7].operator!=(0x11))
                {
                    LangureStr_Init_BurnData_Failed(ui->te_prin_disp_f210);
                    WriteFile.close();
                    return false;
                }
                hexEdit_code_f210->append(WriteBuff);
            }
            else
            {
                WriteFile.close();
                return false;
            }
        }
        else
        {
            break;
        }
        // 计次，不能为255
        icnt++;
    }
    //
    WriteFile.close();
    ComThread_disp_f210->SendSerial_Write_GammaData(LineBuff, 0xff);
    while(RespData_disp_f210.isEmpty())QApplication::processEvents();

    LangureStr_Init_BurnData_Succeed(ui->te_prin_disp_f210);
    return true;
}

//锁定解锁状态分支
void MainWindow::Btn_Lock_Or_Unlock_Disp_F210(int EnabledStu)
{
    switch(EnabledStu) {
    case DISP_BTN_LOCK_ALL:{
        ui->btn_disp_read_f210->setEnabled(false);
        ui->btn_disp_write_f210->setEnabled(false);
        ui->cbx_disp_write_f210->setEnabled(false);
        break;
    }
    case DISP_BTN_UNLOCK_ALL:
    case DISP_BTN_LOCK_RES:{
        //
        ui->btn_disp_read_f210->setEnabled(true);
        ui->btn_disp_write_f210->setEnabled(false);
        ui->cbx_disp_write_f210->setEnabled(true);
        break;
    }
    }
    //
    ui->cbx_disp_write_f210->setCheckState(Qt::Unchecked);
}

void MainWindow::on_cbx_disp_write_f210_clicked()
{
    bool CbxStu = ui->cbx_disp_write_f210->isChecked();
    ui->btn_disp_write_f210->setEnabled(CbxStu);
}
